from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from apps.article.models import Channel, Article
from apps.article.serializers import ChannelsSerializer, UploadArticlesSerializer, CommentSerializer, \
    ListArticleSerializer, ArticleSearchSerializer, DetailArticleSerializer


# Create your views here.

# 获取首页频道列表
class ChannelView(ListAPIView):
    queryset = Channel.objects.all()
    serializer_class = ChannelsSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response({'results': serializer.data})


class ArticleViewSet(ModelViewSet):
    queryset = Article.objects.all()

    # 发布文章
    def create(self, request, *args, **kwargs):
        user = request.user
        if user is not None and user.is_authenticated:
            request_params = request.data
            request_params['user'] = user.id
            ser = UploadArticlesSerializer(data=request_params)
            ser.request = request
            try:
                ser.is_valid(raise_exception=True)
            except Exception as e:
                print(e)
                return Response({'success': False, 'message': '验证失败'}, status=400)

            article = ser.save()
            return Response({'success': True, 'message': '发表成功', 'articleid': article.id})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)

    # 文章详情页
    def retrieve(self, request, *args, **kwargs):
        article = super().get_object()
        article.visits += 1
        article.save()
        ser = DetailArticleSerializer(article)
        return Response(ser.data)


    # 获取频道下的文章列表
    @action(methods=['get'], detail=True)
    def channel(self, request, pk):
        if pk == "-1":
            articles = self.get_queryset()
        else:
            channel = Channel.objects.filter(id=pk)
            articles = self.queryset.filter(channel=channel)

        page = self.paginate_queryset(articles)
        if page is not None:
            ser = self.get_serializer(page, many=True)
            return self.get_paginated_response(ser.data)
        else:
            ser = ListArticleSerializer(articles, many=True)
            return Response({"results": ser.data})

    # 收藏文章
    @action(methods=['put'], detail=True)
    def collect(self, request, pk):
        user = request.user
        if user is not None and user.is_authenticated:
            article = self.get_object()
            if user not in article.collected_users.all():
                article.collected_users.add(user)
                article.save()
                return Response({'success': True, 'message': '收藏成功'})
            else:
                article.collected_users.remove(user)
                article.save()
                return Response({'success': True, 'message': '取消收藏成功'})
        else:

            return Response({'success': False, 'message': '未登录'}, status=400)

    # 评论文章
    @action(methods=['post'], detail=True)
    def publish_comment(self, request, pk):
        user = request.user
        if user is not None and user.is_authenticated:
            article = self.get_object()
            article.comment_count += 1
            article.save()
            request_params = request.data
            request_params['user'] = user.id
            request_params['article'] = article.id
            ser = CommentSerializer(data=request_params)
            ser.is_valid(raise_exception=True)
            ser.save()
            return Response({'success': True, 'message': '评论成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)


# 根据关键字搜索文章
class ArticleSearchView(APIView):
    def get(self, request):
        a = request.query_params['text']
        articles = Article.objects.filter(title__contains=a)
        serializer = ArticleSearchSerializer(articles, many=True)
        return Response({"results": serializer.data})
